package com.yanqu.road.server.manger.config;

import com.yanqu.road.entity.config.beauty.BeautyInfo;
import com.yanqu.road.entity.config.passroad.PassRoadEventInfo;
import com.yanqu.road.entity.config.passroad.PassRoadInfo;
import com.yanqu.road.entity.config.passroad.PassRoadPointInfo;
import com.yanqu.road.entity.config.passroad.PassRoadTransportInfo;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.ePassRoadEventType;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.player.UserPassRoad;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.logic.bussiness.config.PassRoadBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.passRoad.PassTransportModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.curio.CurioMgr;
import com.yanqu.road.server.manger.player.TradeWarMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.math.BuildCombine;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  关卡改经商之路
 */
public class PassRoadMgr extends TempMgr {

	private static Logger logger = LogManager.getLogger(TradeWarMgr.class.getName());

	//原始数据
	private static Map<Integer, PassRoadInfo> passRoadInfoMap;

	private static Map<Integer, PassRoadEventInfo> passRoadEventInfoMap;

	private static Map<Integer,Map<Integer,PassRoadPointInfo>> passRoadPointInfoMap ;

	//兼容以前的都东西，最大的passId,活动中用到和建筑中用到，因为关卡改成了可以打到最后一关提示不能再打了，之前是打最后一关会无限循环
	//所以会保存一个不存在的关卡信息，会获取到错误的关卡信息，当获取到的是空的关卡信息的时候就用这个id去做处理
	private static PassRoadPointInfo lastPassRoadPointInfo;

	private static PassRoadInfo firstPassRoadInfo;

	private static PassRoadInfo lastPassRoadInfo;

	private static Map<Integer, PassRoadTransportInfo> passRoadTransportInfoMap;

	// 每个关卡point的起始rankId
	private static Map<Integer, Integer> rankStartIdMap;

	// 每个关卡的最近使用时间
	private static Map<Integer, Integer> passInfoUseTimeMap = new ConcurrentHashMap<>();

	// 需要移除的关卡列表
	private static Set<Integer> needRemovePassPointIdSet = new HashSet<>();

	// 当前解析到的rankId
	public static int globalRankId;


	@Override
	public boolean stop() {
		return false;
	}

	@Override
	public boolean save() {
		return false;
	}

	@Override
	public boolean init() throws Exception {
		return reload();
	}

	@Override
	public boolean reloadConfig() {
		passRoadInfoMap = PassRoadBussiness.getRoadInfoMap();
		passRoadEventInfoMap = PassRoadBussiness.getRoadEventInfoMap();
		passRoadTransportInfoMap = PassRoadBussiness.getRoadTransportInfoMap();
		rankStartIdMap = new HashMap<>();
		findFirstRoadInfo();
		initRoadProgressIdMap();
		if(null == firstPassRoadInfo){
			return false;
		}
		if(null == lastPassRoadInfo){
			return false;
		}
		if(null == lastPassRoadPointInfo){
			return false;
		}
		for (PassRoadInfo passRoadInfo : passRoadInfoMap.values()) {
			passRoadInfo.clearUsedLessObject();
		}
		return true;
	}

	@Override
	public boolean reloadData() throws Exception {
		return true;
	}

	/**
	 * 如果没有关卡point信息 则从数据库重新加载出数据
	 * @param passId
	 */
	public static Map<Integer,PassRoadPointInfo> getPassPointDataByPassId(int passId) {
		synchronized (passInfoUseTimeMap) {
			passInfoUseTimeMap.put(passId, (int)(System.currentTimeMillis() / 1000));
		}

		// 缓存的结果
		Map<Integer,PassRoadPointInfo> returnPointData = passRoadPointInfoMap.get(passId);

		if (returnPointData == null || returnPointData.size() == 0) {
			Map<Integer,PassRoadPointInfo> pointData = new ConcurrentHashMap<>();
			buildPassRoadPoint(passId, pointData, false);
			passRoadPointInfoMap.put(passId, pointData);
			returnPointData = pointData;
		}


		// 移除冷关卡数据
		if (isUseHotCold()) {
			removePassPointData();
		}
		return returnPointData;
	}

	/**
	 * 移除关卡point数据
	 */
	public static synchronized void removePassPointData() {
		List<Integer> removeList = new ArrayList<>();
		synchronized (needRemovePassPointIdSet) {
			removeList.addAll(needRemovePassPointIdSet);
			needRemovePassPointIdSet.clear();
		}

		for (int passId : removeList) {
			if (passRoadPointInfoMap.containsKey(passId)) {
				passRoadPointInfoMap.get(passId).clear();
				logger.info("remove pass point data  {}", passId);
			}
		}
	}

	/**
	 * 检测需要移除的关卡数据
	 */
	public static void checkWillBeRemovePassId() {
		if (isUseHotCold()) {
			long oneHourBefore = (System.currentTimeMillis() / 1000) - 3600;
			for (Map.Entry<Integer, Integer> entry : passInfoUseTimeMap.entrySet()) {
				int passId = entry.getKey();
				int useTime = entry.getValue();
				if (oneHourBefore >= useTime && passRoadPointInfoMap.containsKey(passId) && passRoadPointInfoMap.get(passId).size() > 0) {
					synchronized (needRemovePassPointIdSet) {
						needRemovePassPointIdSet.add(passId);
					}
				}
			}
		}
	}

	//返回版本更新已经过了老用户的事件奖励
	public static Property getVersionUpdateEventAddReward(UserPassRoad userPassRoad){
		Property sendReward = null;
		int endPassId = userPassRoad.getPassId();
		for(int i = 1;i <= endPassId ; i ++){
			Map<Integer,PassRoadPointInfo> infoMap = passRoadPointInfoMap.get(i);
			for(PassRoadPointInfo info : infoMap.values()){
				if(i == endPassId){
					if(info.getSectionId() >= userPassRoad.getPassProgress() && info.getEventId() != 0){
						continue;
					}
				}
				if(sendReward == null){
					sendReward = new Property();
				}
				sendReward.addProperty(PropertyHelper.parseStringToProperty(passEventUpdateReward(getPassRoadEventInfo(info.getEventId()))));
			}
		}
		return sendReward;
	}


	private void findFirstRoadInfo() {
		int minRoadId = Integer.MAX_VALUE;
		int maxRoadId = Integer.MIN_VALUE;
		for(PassRoadInfo passRoadInfo : passRoadInfoMap.values()){
			if(passRoadInfo.getId() < minRoadId){
				minRoadId = passRoadInfo.getId();
			}
			if(passRoadInfo.getId() > maxRoadId){
				maxRoadId = passRoadInfo.getId();
			}
		}
		firstPassRoadInfo = passRoadInfoMap.get(minRoadId);
		lastPassRoadInfo = passRoadInfoMap.get(maxRoadId);
	}

	public static PassRoadInfo getFirstPassRoadInfo() {
		return firstPassRoadInfo;
	}

	public static PassRoadInfo getLastPassRoadInfo() {
		return lastPassRoadInfo;
	}

	public static PassRoadPointInfo getLastPassRoadPointInfo(){
		return lastPassRoadPointInfo;
	}

	private void initRoadProgressIdMap(){
		//打到最后一个了最后一个记录下
		PassRoadPointInfo lastOne = new PassRoadPointInfo();
		Map<Integer,Map<Integer,PassRoadPointInfo>> roadData = new ConcurrentHashMap<>();
		globalRankId = 1;

		for(int passId = 1;passId <= passRoadInfoMap.size(); passId++) {
			PassRoadInfo passRoadInfo = passRoadInfoMap.get(passId);
			Map<Integer,PassRoadPointInfo> pointData = new ConcurrentHashMap<>();
			roadData.put(passRoadInfo.getId(),pointData);

			// 设置每一个passId的起始rankId
			rankStartIdMap.put(passId, globalRankId);
			lastOne = buildPassRoadPoint(passId, pointData, true);
			// 设置解析到当前的最后一个rankId
			globalRankId = lastOne.getRankId() + 1;

			if (isUseHotCold()) {
				pointData.clear();
			}
		}
		lastPassRoadPointInfo = lastOne;
		passRoadPointInfoMap = roadData;
	}

	/**
	 * 是否采取冷热配置策略
	 * @return
	 */
	public static boolean isUseHotCold() {
		ServerInfo serverInfo = ServerListMgr.getServerInfo(ConfigHelper.getInt("serverId"));
		if (serverInfo.isOpen() && serverInfo.getOpenTime() < ((System.currentTimeMillis() / 1000) - 30 * 24 * 3600)) {
			return true;
		}
		return false;
	}

	/**
	 * 生成passRoadPoint
	 * @param passId
	 * @param pointData
	 * @return
	 */
	public static PassRoadPointInfo buildPassRoadPoint(int passId, Map<Integer,PassRoadPointInfo> pointData, boolean isInit) {
		int rId = rankStartIdMap.get(passId);
		PassRoadPointInfo lastOne = new PassRoadPointInfo();
		PassRoadInfo passRoadInfo;
		if (isInit) {
			passRoadInfo = passRoadInfoMap.get(passId);
		} else {
			passRoadInfo = PassRoadBussiness.getRoadInfoByPassId(passId);
			logger.info("load pass info data from db  {}", passId);
		}
		int processPointId = 0;
		for(int i = 0;i < passRoadInfo.getMoneyList().size();i++){
			for(int j = 0;j < passRoadInfo.getMoneyList().get(i).size();j++){
				PassRoadPointInfo one = new PassRoadPointInfo();
				one.setRankId(rId++);
				one.setId(passRoadInfo.getId());
				one.setSessionId(i);
				one.setSessionSectionId(j);
				one.setSectionId(processPointId++);
				one.setBlood(passRoadInfo.getMoneyList().get(i).get(j));
				one.setAbility(passRoadInfo.getStrengthList().get(i).get(j));
				Property property = new Property();
				property.addProperty(GameConfig.GAME_MONEY_PATRONS_EXP,passRoadInfo.getExperience().get(i).get(j));
				property.addProperty(GameConfig.GAME_MONEY_PRESTIGE,passRoadInfo.getPrestige().get(i).get(j));
				one.setReward(property);
				if(j+1 == passRoadInfo.getMoneyList().get(i).size()){
					one.setSessionEnd(true);
					if(i+1 == passRoadInfo.getMoneyList().size()){
						one.setBoss(true);
					}else{
						one.setEventId(passRoadInfo.getEventsId().get(i));
						one.setEvent(passRoadEventInfoMap.get(one.getEventId()));
					}
				}
				pointData.put(one.getSectionId(),one);
				lastOne = one;

				if (!isInit) {
					logger.debug("passPoint rankId {}", rId);
				}
			}
		}
		return lastOne;
	}


	public static List<PassRoadPointInfo> getPassRoadPointList(int passId){

		Map<Integer,PassRoadPointInfo> pointData = getPassPointDataByPassId(passId);
		return new ArrayList<>(pointData.values());
	}

	public static PassRoadInfo getPassRoadInfo(int passId) {
		return passRoadInfoMap.get(passId);
	}

	public static PassRoadPointInfo getPassRoadPointInfo(int passId, int roadProgress) {
		PassRoadInfo passRoadInfo = getPassRoadInfo(passId);
		if(null != passRoadInfo) {
			Map<Integer,PassRoadPointInfo> pointData = getPassPointDataByPassId(passId);
			return pointData.get(roadProgress);
		}
		return null;
	}

	public static PassRoadEventInfo getPassRoadEventInfo(int eventId) {
		return passRoadEventInfoMap.get(eventId);
	}

	public static List<Integer> getCostMinMaxParam(int passId){
		int minConfigParam = GameConfig.PASS_PATRONS_BATTLE_COST_SILVER_MIN_PARAM;
		int maxConfigParam = GameConfig.PASS_PATRONS_BATTLE_COST_SILVER_MAX_PARAM;
		List<String> paramsList = StringUtils.stringToStringList(GameConfig.PASS_PATRONS_BATTLE_COST_SILVER_PARAM,"\\|");
		for(String params : paramsList){
			List<Integer> paramList = StringUtils.stringToIntegerList(params,"=");
			if(passId < paramList.get(0)){
				minConfigParam = paramList.get(1);
				maxConfigParam = paramList.get(2);
				break;
			}
		}
		List<Integer> paramList = new ArrayList<>();
		paramList.add(0,minConfigParam);
		paramList.add(1,maxConfigParam);
		return paramList;
	}

	public static BigInteger getPassRoadCostSilver(GamePlayer player, PassRoadPointInfo passRoadPointInfo, UserPassRoad userPassRoad) {
		double skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.PassBattleCost.getValue(), 0);
		skillAddition += player.getModule(PatronsModule.class).getTalentSkillAddition(eSkillType.PassBattleCost.getValue(), 0);
		//坐骑减少
		double transportAddition = player.getModule(PassTransportModule.class).getTransportSilverAddition();
		BigDecimal patronsAbility = new BigDecimal(PatronsMgr.getPatronsTotalAbility(userPassRoad.getUserId()));
		BigDecimal enemyAbility = new BigDecimal(passRoadPointInfo.getAbility());
		BigDecimal damage = enemyAbility.divide(patronsAbility, 4, BigDecimal.ROUND_UP);


		List<Integer> paramList = getCostMinMaxParam(passRoadPointInfo.getId());
		BigDecimal minParam = BigDecimal.valueOf((double) paramList.get(0) / 1000);
		BigDecimal maxParam = BigDecimal.valueOf((double) paramList.get(1) / 1000);
		if (minParam.compareTo(damage) > 0) {
			damage = minParam;
		}
		if (damage.compareTo(maxParam) > 0) {
			damage = maxParam;
		}
		BigDecimal enemyCurrentBlood = new BigDecimal(passRoadPointInfo.getBlood());
		enemyCurrentBlood = enemyCurrentBlood.multiply(damage);
		enemyCurrentBlood = enemyCurrentBlood.
				multiply(BigDecimal.valueOf(skillAddition / 1000 + 1)).
				multiply(BigDecimal.valueOf(transportAddition / 1000 + 1)).
				setScale(0, BigDecimal.ROUND_UP);
		return enemyCurrentBlood.toBigInteger();
	}

	//新版银两消耗
	public static BigInteger getPassRoadCostSilver121(GamePlayer player, PassRoadPointInfo passRoadPointInfo, UserPassRoad userPassRoad) {
		double skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.PassBattleCost.getValue(), 0);
		skillAddition += player.getModule(PatronsModule.class).getTalentSkillAddition(eSkillType.PassBattleCost.getValue(), 0);
		//坐骑减少
		double transportAddition = player.getModule(PassTransportModule.class).getTransportSilverAddition();
		BigDecimal patronsAbility = new BigDecimal(PatronsMgr.getPatronsTotalAbility(userPassRoad.getUserId()));
		BigDecimal enemyAbility = new BigDecimal(passRoadPointInfo.getAbility());
		BigDecimal damage = enemyAbility.divide(patronsAbility, 4, BigDecimal.ROUND_UP);

		double addition = (double) CurioMgr.getSkillAdditionBySkillType(eSkillType.CurioPassBattleCostSkill.getValue(), player, 0);

		damage = BigDecimal.valueOf(Math.pow(damage.doubleValue(),(double)GameConfig.PASS_PATRONS_BATTLE_COST_SILVER_PARAM1/1000)).
				multiply(BigDecimal.valueOf(skillAddition / 1000 + 1)).
				multiply(BigDecimal.valueOf((transportAddition - addition) / 1000 + 1)).
				setScale(4, BigDecimal.ROUND_UP);

		List<Integer> paramList = getCostMinMaxParam(passRoadPointInfo.getId());
		BigDecimal minParam = BigDecimal.valueOf((double) paramList.get(0) / 1000);
		BigDecimal maxParam = BigDecimal.valueOf((double) paramList.get(1) / 1000);
		if (minParam.compareTo(damage) > 0) {
			damage = minParam;
		}
		if (damage.compareTo(maxParam) > 0) {
			damage = maxParam;
		}
		BigDecimal enemyCurrentBlood = new BigDecimal(passRoadPointInfo.getBlood());
		enemyCurrentBlood = enemyCurrentBlood.multiply(damage).setScale(0, BigDecimal.ROUND_UP);
		return enemyCurrentBlood.toBigInteger();
	}

	public static BigDecimal getPassRoadCostSilver121damage(GamePlayer player, PassRoadPointInfo passRoadPointInfo, UserPassRoad userPassRoad) {
		double skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.PassBattleCost.getValue(), 0);
		skillAddition += player.getModule(PatronsModule.class).getTalentSkillAddition(eSkillType.PassBattleCost.getValue(), 0);
		//坐骑减少
		double transportAddition = player.getModule(PassTransportModule.class).getTransportSilverAddition();
		BigDecimal patronsAbility = new BigDecimal(PatronsMgr.getPatronsTotalAbility(userPassRoad.getUserId()));
		BigDecimal enemyAbility = new BigDecimal(passRoadPointInfo.getAbility());
		BigDecimal damage = enemyAbility.divide(patronsAbility, 4, BigDecimal.ROUND_UP);

		return  damage;
	}

	public static BigDecimal getPassRoadCostSilver121damagePow(GamePlayer player, PassRoadPointInfo passRoadPointInfo, UserPassRoad userPassRoad) {
		double skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.PassBattleCost.getValue(), 0);
		skillAddition += player.getModule(PatronsModule.class).getTalentSkillAddition(eSkillType.PassBattleCost.getValue(), 0);
		//坐骑减少
		double transportAddition = player.getModule(PassTransportModule.class).getTransportSilverAddition();
		BigDecimal patronsAbility = new BigDecimal(PatronsMgr.getPatronsTotalAbility(userPassRoad.getUserId()));
		BigDecimal enemyAbility = new BigDecimal(passRoadPointInfo.getAbility());
		BigDecimal damage = enemyAbility.divide(patronsAbility, 4, BigDecimal.ROUND_UP);
		damage = BigDecimal.valueOf(Math.pow(damage.doubleValue(),(double)GameConfig.PASS_PATRONS_BATTLE_COST_SILVER_PARAM1/1000)).
				multiply(BigDecimal.valueOf(skillAddition / 1000 + 1)).
				multiply(BigDecimal.valueOf(transportAddition / 1000 + 1)).
				setScale(4, BigDecimal.ROUND_UP);

		return  damage;
	}

	public static BigInteger getSilverBuyBuffCost(GamePlayer player, BigInteger baseCost, int times) {
		BigInteger cost;
		double skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.PassBossBuyBuffCost.getValue(), 0);
		BigDecimal temp1 = new BigDecimal(baseCost);
		BigDecimal temp2 = BigDecimal.valueOf(ConfigMgr.getPassSilverBuyBuffCost(times));
		cost = temp1.multiply(temp2).multiply(BigDecimal.valueOf(skillAddition / 1000 + 1)).setScale(0, BigDecimal.ROUND_UP).toBigInteger();
		return cost;
	}

	public static long parseRoadProgressId(int passId, int roadProgress){
		Map<Integer,PassRoadPointInfo> pointData =  getPassPointDataByPassId(passId);
		long rankId = 0;
		if(pointData != null) {
			if(pointData.containsKey(roadProgress)){
				return pointData.get(roadProgress).getRankId();
			}
		}
		//打通关后passId已经不存在了
		if(passId == lastPassRoadPointInfo.getId() + 1){
			return lastPassRoadPointInfo.getRankId() + 1;
		}
		return rankId;
	}

	//处理事件逻辑改了passEventReward也要对应改
	public static int passEvent(GamePlayer player,PassRoadEventInfo eventInfo,int selectId, List<Integer> patronIdList, List<Integer> beautyIdList){
		if(eventInfo.getType() == ePassRoadEventType.EventGetReward.getValue()){
			player.getModule(CurrencyModule.class).addCurrency(eventInfo.getRewards(), eLogMoneyType.PassRoadEvent,eLogMoneyType.EventGetReward);
		}else if(eventInfo.getType() == ePassRoadEventType.EventSelectReward.getValue()){
			List<String> rewardList = StringUtils.stringToStringList(eventInfo.getRewards(),"\\|");
			if(selectId >= rewardList.size()){
				return GameErrorCode.E_PASS_ROAD_EVENT_DEAL;
			}
			player.getModule(CurrencyModule.class).addCurrency(rewardList.get(selectId), eLogMoneyType.PassRoadEvent,eLogMoneyType.EventSelectReward);
		}else if(eventInfo.getType() == ePassRoadEventType.EventDispatch.getValue()){
			List<String> conditionList = StringUtils.stringToStringList(eventInfo.getParLists(),"-");
			//不用传满人也可以
			/*if(Integer.valueOf(conditionList.get(0)) != patronIdList.size() + beautyIdList.size()){
				return GameErrorCode.E_PASS_ROAD_EVENT_DISPATCH;
			}*/
			if(!player.getModule(PatronsModule.class).checkPatronsList(patronIdList)){
				return GameErrorCode.E_PASS_ROAD_EVENT_DISPATCH;
			}
			if(!player.getModule(BeautyModule.class).checkBeautyList(beautyIdList)){
				return GameErrorCode.E_PASS_ROAD_EVENT_DISPATCH;
			}
			int star = getEventDispatchStar(player,conditionList.get(1),patronIdList,beautyIdList);
			Property reward = PropertyHelper.parseStringToProperty(eventInfo.getRewards());
			reward.rideProperty(star+1);
			player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.PassRoadEvent,eLogMoneyType.EventSelectReward);
		} else if (eventInfo.getType() == ePassRoadEventType.DecrepitHouseEvent.getValue()) {
			String reward = "";
			String str = eventInfo.getParLists();
			String s = str.split("=")[1];
			String[] arr = s.split("\\|");
			int rewardIndex = -1;
			for (int i = 0; i < arr.length; i++) {
				String[] split = arr[i].split(";");
				int min = Integer.parseInt(split[0]);
				int max = Integer.parseInt(split[1]);
				if (selectId >= min && selectId <= max) {
					rewardIndex = i;
					break;
				}
			}
			if (rewardIndex >= 0) {
				String rewards = eventInfo.getRewards();
				String[] rewardArr = rewards.split("\\|");
				if (rewardArr.length > rewardIndex) {
					String s1 = rewardArr[rewardIndex];
					if (!"0".equals(s1)) {
						reward = s1;
					}
				}
			}
			player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.PassRoadEvent,eLogMoneyType.EventSelectReward);
		} else if (eventInfo.getType() == ePassRoadEventType.SaveDogEvent.getValue()) {
			if (selectId == 1) {
				player.getModule(CurrencyModule.class).addCurrency(eventInfo.getRewards(), eLogMoneyType.PassRoadEvent, eLogMoneyType.EventSaveDogReward);
			}
		} else if (eventInfo.getType() == ePassRoadEventType.SmallGameEvent.getValue()) {
			player.getModule(CurrencyModule.class).addCurrency(eventInfo.getRewards(), eLogMoneyType.PassRoadEvent, eLogMoneyType.EventSmallGameReward);
		} else {
			logger.error("未知主线事件player:{},eventType:{}", player.getUserId(), eventInfo.getType());
			return GameErrorCode.E_PASS_ROAD_EVENT_UNKNOWN;
		}
		return 0;
	}

	//获取处理事件的奖励
	public static String passEventReward(GamePlayer player,PassRoadEventInfo eventInfo,int selectId, List<Integer> patronIdList, List<Integer> beautyIdList){
		if(eventInfo.getType() == ePassRoadEventType.EventGetReward.getValue()){
			return eventInfo.getRewards();
		}else if(eventInfo.getType() == ePassRoadEventType.EventSelectReward.getValue()){
			List<String> rewardList = StringUtils.stringToStringList(eventInfo.getRewards(),"\\|");
			if(selectId >= rewardList.size()){
				return "";
			}
			return rewardList.get(selectId);
		}else if(eventInfo.getType() == ePassRoadEventType.EventDispatch.getValue()){
			List<String> conditionList = StringUtils.stringToStringList(eventInfo.getParLists(),"-");
			if(!player.getModule(PatronsModule.class).checkPatronsList(patronIdList)){
				return "";
			}
			if(!player.getModule(BeautyModule.class).checkBeautyList(beautyIdList)){
				return "";
			}
			int star = getEventDispatchStar(player,conditionList.get(1),patronIdList,beautyIdList);
			Property reward = PropertyHelper.parseStringToProperty(eventInfo.getRewards());
			reward.rideProperty(star+1);
			return PropertyHelper.parsePropertyToString(reward);
		} else if (eventInfo.getType() == ePassRoadEventType.DecrepitHouseEvent.getValue()) {
			String str = eventInfo.getParLists();
			String s = str.split("=")[1];
			String[] arr = s.split("\\|");
			int rewardIndex = -1;
			for (int i = 0; i < arr.length; i++) {
				String[] split = arr[i].split(";");
				int min = Integer.parseInt(split[0]);
				int max = Integer.parseInt(split[1]);
				if (selectId >= min && selectId <= max) {
					rewardIndex = i;
					break;
				}
			}
			if (rewardIndex >= 0) {
				String rewards = eventInfo.getRewards();
				String[] rewardArr = rewards.split("\\|");
				if (rewardArr.length > rewardIndex) {
					String s1 = rewardArr[rewardIndex];
					if (!"0".equals(s1)) {
						return s1;
					}
				}
			}
			return "";
		} else if (eventInfo.getType() == ePassRoadEventType.SaveDogEvent.getValue()) {
			return selectId == 1 ? eventInfo.getRewards() : ""; // 1完成才有奖励
		} else if (eventInfo.getType() == ePassRoadEventType.SmallGameEvent.getValue()) {
			return eventInfo.getRewards();
		} else {
			return "";
		}
	}

	//版本更新的时候老用户的过往事件通过邮件奖励发放
	//	1、奖励事件：按事件奖励补偿
	//2、选项事件：按对应事件第一选项奖励进行补偿
	//3、派遣事件：按派遣事件最高星级奖励进行补偿
	public static String passEventUpdateReward(PassRoadEventInfo eventInfo){
		if(eventInfo == null){
			return "";
		}
		if(eventInfo.getType() == ePassRoadEventType.EventGetReward.getValue()){
			return eventInfo.getRewards();
		}else if(eventInfo.getType() == ePassRoadEventType.EventSelectReward.getValue()){
			List<String> rewardList = StringUtils.stringToStringList(eventInfo.getRewards(),"\\|");
			return rewardList.get(0);
		}else if(eventInfo.getType() == ePassRoadEventType.EventDispatch.getValue()){
			List<String> conditionList = StringUtils.stringToStringList(eventInfo.getParLists(),"-");
			List<String> conditionStarList = StringUtils.stringToStringList(conditionList.get(1),"\\|");
			Property reward = PropertyHelper.parseStringToProperty(eventInfo.getRewards());
			reward.rideProperty(conditionStarList.size()+1);
			return PropertyHelper.parsePropertyToString(reward);
		}else {
			return "";
		}
	}


	//5-3;102451;0|1;4;0|1;4;0|1;4;0|1;4;0|1;4;0-----------------（1门客2美女）类型;品质;职业;个数-34类型;门客美女id;0;0
	public static int getEventDispatchStar(GamePlayer player,String conditionStr ,List<Integer> patronIdList, List<Integer> beautyIdList){
		int star = 0;
		Map<Integer,List<Integer>> pMap = player.getModule(PatronsModule.class).getDispatchList(patronIdList);
		Map<Integer,List<Integer>> bMap = player.getModule(BeautyModule.class).getDispatchList(beautyIdList);
		List<String> conditionList = StringUtils.stringToStringList(conditionStr,"\\|");
		for(String condition : conditionList){
			List<Integer> paramList = StringUtils.stringToIntegerList(condition,";");
			int param1 = paramList.get(0);
			int param2 = paramList.get(1);
			int param3 = paramList.get(2);
			int param4 = paramList.get(3);
			if(paramList.size() != 4){
				return 0;
			}
			if(param1 == 1){//门客
				int patronNum = 0;
				if(pMap.containsKey(param3)){
					for(Integer quality : pMap.get(param3)){
						if(quality >= param2){
							patronNum++;
						}
					}
				}
				if(patronNum >= param4){
					star++;
				}
			}else if(param1 == 2){//美女
				int beautyNum = 0;
				if(bMap.containsKey(param3)){
					for(Integer quality : bMap.get(param3)){
						if(quality >= param2){
							beautyNum++;
						}
					}
				}
				if(beautyNum >= param4){
					star++;
				}
			}else if(param1 == 3){//指定门客
				if(patronIdList.contains(param2)){
					star++;
				}
			}else if(param1 == 4){//指定美女
				if(beautyIdList.contains(param2)){
					star++;
				}
			}
		}
		return star;
	}

	public static PassRoadTransportInfo getTransportInfo(int tpId){
	    return passRoadTransportInfoMap.get(tpId);
    }

	/**
	 * 自动处理事件
	 */
	public static String autoDealPassEventReward(GamePlayer player, PassRoadEventInfo eventInfo){
		if(null == eventInfo){
			return "";
		}
		if(eventInfo.getType() == ePassRoadEventType.EventGetReward.getValue()){
			return eventInfo.getRewards();
		}else if(eventInfo.getType() == ePassRoadEventType.EventSelectReward.getValue()){
			List<String> rewardList = StringUtils.stringToStringList(eventInfo.getRewards(),"\\|");
			return rewardList.get(0);
		}else if(eventInfo.getType() == ePassRoadEventType.EventDispatch.getValue()){
			List<String> conditionList = StringUtils.stringToStringList(eventInfo.getParLists(),"-");
			int maxStar = getMaxStar(player, Integer.valueOf(conditionList.get(0)), conditionList.get(1));
			Property reward = PropertyHelper.parseStringToProperty(eventInfo.getRewards());
			reward.rideProperty(maxStar + 1);
			return PropertyHelper.parsePropertyToString(reward);
		}else {
			return "";
		}

	}

	/**
	 * 获取最大星数
	 * @param player
	 * @param siteNum
	 * @param conditionStr
	 * @return
	 */
	private static int getMaxStar(GamePlayer player, int siteNum, String conditionStr) {
		int star = 0;
		long nowTime = System.currentTimeMillis();
		PatronsModule patronsModule = player.getModule(PatronsModule.class);
		BeautyModule beautyModule = player.getModule(BeautyModule.class);

		// 已有门客及美女列表
		List<Integer> patronsList = new ArrayList<>(patronsModule.getUserPatronsMap().keySet());
		List<Integer> beautyList = new ArrayList<>(beautyModule.getBeautyMap().keySet());
		List<String> conditionStarList = StringUtils.stringToStringList(conditionStr,"\\|");
		logger.info("=====get max start max star:{}", conditionStarList.size());

		List<String> patronsCondition = new ArrayList<>();
		List<String> beautyCondition = new ArrayList<>();

		//指定门客、美女
		Set<Integer> appointPatronsSet = new HashSet<>();
		Set<Integer> appointBeautySet = new HashSet<>();

		Set<Integer> rightPatronsList = new HashSet<>();
		Set<Integer> rightBeautyList = new HashSet<>();
		// 优先处理3跟4的事件
		for (String condition : conditionStarList) {
			List<Integer> paramList = StringUtils.stringToIntegerList(condition,";");
			int param1 = paramList.get(0);
			int param2 = paramList.get(1);
			int param3 = paramList.get(2);

			if (param1 == 3) {
				if (patronsList.contains(param2)) {
					star++;
					siteNum --;
					appointPatronsSet.add(param2);
				}
			} else if (param1 == 4) {
				if (beautyList.contains(param2)) {
					star++;
					siteNum --;
					appointBeautySet.add(param2);
				}
			} else if (param1 == 1) {
				patronsCondition.add(condition);

				// 提取出满足条件的门客
				for (int patronId : patronsList) {
					PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(patronId);
					if (patronsInfo == null) {
						continue;
					}
					if ((param3 == patronsInfo.getOccupation() || 0 == param3) && patronsInfo.getQuality() >= param2) {
						rightPatronsList.add(patronId);
					}
				}


			} else if (param2 == 2) {
				beautyCondition.add(condition);

				// 提取出满足条件的美女
				for (int beautyId : beautyList) {
					BeautyInfo beautyInfo = BeautyMgr.getBeautyInfo(beautyId);
					if (beautyInfo == null) {
						continue;
					}
					if ((param3 == beautyInfo.getOccupation() || 0 == param3) && beautyInfo.getQuality() >= param2) {
						rightBeautyList.add(beautyId);
					}
				}

			}
		}

		//移除指定
		rightPatronsList.removeAll(appointPatronsSet);
		rightBeautyList.removeAll(appointBeautySet);

		int remainMaxStar = beautyCondition.size() + patronsCondition.size();
		if (siteNum == 0 || remainMaxStar == 0) {
			logger.info("======get max start use:{} ms, max star:{}", System.currentTimeMillis() - nowTime, star);
			return star;
		}

		if (patronsCondition.size() > 0 && beautyCondition.size() == 0) {
			// 只有门客需要
			if (siteNum >= rightPatronsList.size()) {
				// 人数不够坑位个数
				List<Integer> tempPatronsList = new ArrayList<>(appointPatronsSet);
				tempPatronsList.addAll(rightPatronsList);
				star = getEventDispatchStar(player, conditionStr, tempPatronsList, new ArrayList<>());
			} else {
				// 人数超过坑位个数
				List<List<Integer>> combineList = new BuildCombine(new ArrayList<>(rightPatronsList), siteNum).getCombineList();
				for (List<Integer> list : combineList) {
					List<Integer> tempPatronsList = new ArrayList<>(appointPatronsSet);
					tempPatronsList.addAll(list);
					int cStar = getEventDispatchStar(player, conditionStr, tempPatronsList, new ArrayList<>());
					if (cStar > star) {
						star = cStar;
					}
					if (star == conditionStarList.size()) {
						// 达到最大星数
						break;
					}
				}
			}
		} else if (patronsCondition.size() == 0 && beautyCondition.size() > 0) {
			// 只有美女需要
			if (siteNum >= rightBeautyList.size()) {
				List<Integer> tempBeautyList = new ArrayList<>(appointBeautySet);
				tempBeautyList.addAll(rightBeautyList);
				star = getEventDispatchStar(player, conditionStr, new ArrayList<>(), tempBeautyList);
			} else {
				// 人数超过坑位个数
				List<List<Integer>> combineList = new BuildCombine(new ArrayList<>(rightBeautyList), siteNum).getCombineList();
				for (List<Integer> list : combineList) {
					List<Integer> tempBeautyList = new ArrayList<>(appointBeautySet);
					tempBeautyList.addAll(list);
					int cStar = getEventDispatchStar(player, conditionStr, new ArrayList<>(), tempBeautyList);
					if (cStar > star) {
						star = cStar;
					}
					if (star == conditionStarList.size()) {
						// 达到最大星数
						break;
					}
				}
			}
		} else {
			// 两种都需要
			List<Integer> allList = new ArrayList<>();
			allList.addAll(rightPatronsList);
			allList.addAll(rightBeautyList);

			if (allList.size() <= siteNum) {
				List<Integer> tempPatronsList = new ArrayList<>(appointPatronsSet);
				tempPatronsList.addAll(rightPatronsList);
				List<Integer> tempBeautyList = new ArrayList<>(appointBeautySet);
				tempBeautyList.addAll(rightBeautyList);
				star = getEventDispatchStar(player, conditionStr, tempPatronsList, tempBeautyList);
			} else {
				List<List<Integer>> combineList = new BuildCombine(allList, siteNum).getCombineList();
				for (List<Integer> list : combineList) {
					List<Integer> p = new ArrayList<>();
					List<Integer> b = new ArrayList<>();
					for (int id : list) {
						if (rightPatronsList.contains(id)) {
							p.add(id);
						} else if (rightBeautyList.contains(id)) {
							b.add(id);
						}
					}
					p.addAll(appointPatronsSet);
					p.addAll(appointBeautySet);

					int cStar = getEventDispatchStar(player, conditionStr, p, b);
					if (cStar > star) {
						star = cStar;
					}
					if (star == conditionStarList.size()) {
						// 达到最大星数
						break;
					}
				}
			}
		}
		logger.info("======get max start use:{} ms, max star:{}", System.currentTimeMillis() - nowTime, star);
		return star;
	}
}
